// https://blog.csdn.net/m0_73884922/article/details/139971295

import { cellToRange, FUniver, LocaleType } from '@univerjs/presets'
import { ScrollToCellCommand } from '@univerjs/sheets-ui'
import { SetSelectionsOperation, ClearSelectionFormatCommand } from '@univerjs/sheets'

import { ref } from 'vue'

export const useSheetApiTest = () => {
  const univerAPIRef = ref<FUniver | null>()
  const setRef = (val: FUniver) => {
    univerAPIRef.value = val
  }

  const getData = () => {
    const fWorkbook = univerAPIRef.value?.getActiveWorkbook()
    const snapshot = fWorkbook?.save()
    console.log(snapshot)
  }

  const setValue = () => {
    // 获取当前表数据
    const activeSheet = univerAPIRef.value?.getActiveWorkbook()!.getActiveSheet()!

    // 设置单元格 value
    const range = activeSheet.getRange(0, 0)
    if (!range) {
      throw new Error('range is not defined')
    }
    range.setValue('123312')
  }

  const setRangeValue = () => {
    // 设置某个范围单元格数据
    const values = [
      ['Hello', 'World!'],
      ['Hello', 'Univer!'],
    ]
    const activeSheet = univerAPIRef.value?.getActiveWorkbook()!.getActiveSheet()!
    const range = activeSheet.getRange(0, 0, values.length, values[0].length)
    // getRange对应的从第0行第0列，到第X行，第X列（索引0开始）
    if (!range) throw new Error('range is not defined')
    range.setValues(values)
  }

  // https://docs.univer.ai/zh-CN/guides/sheets/features/core/sheet-api#获取工作表数据

  const getValue = () => {
    // 获取某个单元格 value => getRange => 第X行，第X列, 到 到第X行，第X列（索引0开始）
    const activeSheet = univerAPIRef.value?.getActiveWorkbook()!.getActiveSheet()!
    const range = activeSheet.getRange(0, 0, 2, 2)
    if (!range) throw new Error('range is not defined')

    const data: (string | undefined)[][] = []
    range.forEach((row, col, cell) => {
      data[row] = data[row] || []
      data[row][col] = cell.v?.toString()
    })
    console.log(data)
  }

  const getWorkBookData = () => {
    // 获取workbookData 和传入的数据格式一致
    const activeWorkbook = univerAPIRef.value?.getActiveWorkbook()!
    if (!activeWorkbook) throw new Error('activeWorkbook is not defined')

    console.log(JSON.stringify(activeWorkbook.getSnapshot(), null, 2))
  }

  const getSheetData = () => {
    // 获取sheetData 数据 -> 是获取workbookData中的sheet中的data
    const activeWorkbook = univerAPIRef.value?.getActiveWorkbook()
    if (!activeWorkbook) throw new Error('activeWorkbook is not defined')

    const snapshot = activeWorkbook.getSnapshot()
    const sheet1 = Object.values(snapshot.sheets).find((sheet) => {
      return sheet.id === 'RSfWjJFv4opmE1JaiRj80'
    })
    console.log(sheet1?.cellData)
  }

  const createSheet = () => {
    // { sheets:{sheet1:{}, Sheet2:{}}}
    // 创建sheet
    const activeWorkbook = univerAPIRef.value?.getActiveWorkbook()
    const sheet = activeWorkbook?.create('Sheet2', 10, 10) // 设置10行10列表格
    const cell = sheet?.getRange(0, 1)
    cell?.setValue('123')
  }

  const scrollTo = () => {
    // scroll to B100
    // 函数式
    // const activeWorkbook = univerAPIRef.value?.getActiveWorkbook()
    // const fWorksheet = activeWorkbook?.getActiveSheet()
    // fWorksheet?.scrollToCell(0, 0)

    // 命令式
    const id = ScrollToCellCommand.id // 'sheet.command.scroll-to-cell'
    univerAPIRef.value?.executeCommand(id, {
      range: {
        startRow: 0, // A1 的行索引（0-based）
        endRow: 0,
        startColumn: 0, // A1 的列索引（0-based）
        endColumn: 0,
      },
    })
  }

  const scrollToBottom = () => {
    const activeSheet = univerAPIRef.value?.getActiveWorkbook()!.getActiveSheet()!

    // scroll to bottom
    const rowCount = activeSheet.getSheet().getRowCount()

    const id = ScrollToCellCommand.id // 'sheet.command.scroll-to-cell'
    univerAPIRef.value?.executeCommand(id, {
      range: {
        startRow: 0, // A1 的行索引（0-based）
        endRow: rowCount,
        startColumn: 0, // A1 的列索引（0-based）
        endColumn: 0,
      },
    })
  }

  const setCellBackground = () => {
    const activeSheet = univerAPIRef.value?.getActiveWorkbook()!.getActiveSheet()!
    // 设置单元格背景
    // const range = activeSheet.getRange(0, 0, 1, 1)
    const range = activeSheet.getActiveCell()
    range?.setBackgroundColor('red')
  }

  const focusCell = () => {
    const activeWorkbook = univerAPIRef.value?.getActiveWorkbook()!
    const activeSheet = activeWorkbook!.getActiveSheet()!
    // 聚焦单元格
    const subUnitId = activeSheet.getSheet().getSheetId()
    // activeSheet.setActiveSelection
    // activeSheet.setActiveSelection(activeSheet.getRange('A10:B10'))

    activeSheet.getSelection()
    const id = SetSelectionsOperation.id // 'sheet.operation.set-selections'
    univerAPIRef.value?.executeCommand(id, {
      selections: [
        {
          range: {
            startRow: 0,
            startColumn: 0,
            endRow: 0,
            endColumn: 0,
            rangeType: 0,
          },
        },
      ],
      subUnitId,
      unitId: activeWorkbook.getId(),
      type: 2,
    })
  }

  const clearCellStyle = async () => {
    const activeWorkbook = univerAPIRef.value?.getActiveWorkbook()!

    const activeSheet = univerAPIRef.value?.getActiveWorkbook()!.getActiveSheet()!
    // 清除A1 styles
    const subUnitId = activeSheet.getSheet().getSheetId()

    const id = SetSelectionsOperation.id // 'sheet.operation.set-selections'
    await univerAPIRef.value?.executeCommand(id, {
      selections: [
        {
          range: {
            startRow: 0,
            startColumn: 0,
            endRow: 0,
            endColumn: 0,
            rangeType: 0,
          },
        },
      ],
      subUnitId,
      unitId: activeWorkbook.getId(),
      type: 2,
    })

    // 清除当前单元格格式
    // activeSheet.getRange('A0').clearFormat()

    const clearId = ClearSelectionFormatCommand.id // sheet.command.clear-selection-format
    univerAPIRef.value?.executeCommand(clearId)
  }

  const resizeColsWidth = () => {
    const activeSheet = univerAPIRef.value?.getActiveWorkbook()!.getActiveSheet()!
    activeSheet?.autoResizeColumns(0, 18)
  }

  const recover = () => {
    // univerAPIRef.value?.getActiveWorkbook()?.dispose()
    const activeSheet = univerAPIRef.value?.getActiveWorkbook()?.getActiveSheet()!
    univerAPIRef.value
      ?.getActiveWorkbook()
      ?.deleteSheet(univerAPIRef.value?.getActiveWorkbook()?.getActiveSheet()!)

    univerAPIRef.value?.getActiveWorkbook()?.insertSheet(activeSheet.getSheetName())

    // univerAPIRef.value?.createWorkbook({
    //   id: 'gyI0JO',
    //   name: '',
    //   appVersion: '0.5.0',
    //   locale: LocaleType.ZH_CN,
    //   styles: {},
    //   sheetOrder: ['RSfWjJFv4opmE1JaiRj80'],
    //   sheets: {
    //     RSfWjJFv4opmE1JaiRj80: {
    //       cellData: {},
    //       id: 'RSfWjJFv4opmE1JaiRj80',
    //     },
    //   },
    //   resources: [
    //     {
    //       name: 'SHEET_DEFINED_NAME_PLUGIN',
    //       data: '',
    //     },
    //   ],
    // })
  }

  return {
    getData,
    setRef,
    setValue,
    setRangeValue,
    getValue,
    getWorkBookData,
    getSheetData,
    createSheet,
    scrollTo,
    scrollToBottom,
    setCellBackground,
    focusCell,
    clearCellStyle,
    resizeColsWidth,
    recover,
  }
}
